<template>
<el-scrollbar style="height:100%;">
	<div class="container p-40">
		<div>
			<el-form
				ref="basicForm"
				v-loading="loading"
				:rules="rules"
				:model="basicForm"
				label-width="100px"
			>
				<p class="f-17 m-b-20">设备信息</p>
				<el-row :gutter="40">
					<el-col :span="8">
						<el-form-item
							label="设备类型"
							prop="fkEquipmentTypeId"
							:rules="[
								{ required: true, message: '请选择设备类型' }
							]"
						>
							<el-select
								placeholder="请输入"
								v-model="basicForm.fkEquipmentTypeId"
							>
								<el-option
									v-for="item in equipment"
									:key="item.pkBasicdataId"
									:value="item.pkBasicdataId"
									:label="item.itemName"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="设备名称"
							prop="equipmentName"
						>
							<el-input
								placeholder="请输入"
								v-model="basicForm.equipmentName"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="设备序列号"
							prop="equipmentSerialNumber"
							:rules="[
								{ required: true, message: '请输入设备序列号' }
							]"
						>
							<el-input
								placeholder="请输入"
								v-model="basicForm.equipmentSerialNumber"
								:disabled = "this.isUpdate"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="40">
					<el-col :span="8">
						<el-form-item label="设备IP地址" >
							<el-input
								placeholder="请输入"
								v-model="basicForm.deviceIpAddress"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item 
						prop = "brand"
						label="品牌"
						:rules="[
								{ required: true, message: '请输入品牌' }
							]"
						>
							<el-input
								placeholder="请输入"
								v-model="basicForm.brand"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="所属楼宇"
							prop="fkBuildingId"
							:rules="[
								{
									required: true,
									message: '请选择所属楼宇',
									trigger: 'blur'
								}
							]"
						>
							<el-select
								clearable
								@change="changeBuilding"
								placeholder="请输入"
								v-model="basicForm.fkBuildingId"
							>
								<el-option
									v-for="(item, index) in building"
									:label="item.buildingName"
									:key="index"
									:value="item.pkBuildingId"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="40">
					<el-col :span="8">
						<el-form-item
							label="所属区域"
							prop="region"
							:rules="
                            [
								{
									required: true,
									message: '请选择所属区域',
									trigger: 'blur'
								}
							]">
							<el-select
								clearable
								placeholder="请输入"
								v-model="basicForm.region"
							>
								<el-option
									v-for="item in rooms"
									:key="item.pkRoomId"
									:value="item.pkRoomId"
									:label="item.houseNumber"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<template v-if="isChopper">
						<el-col :span="8">
							<el-form-item
								label="断路器类型"
								prop="fkEquipmentModelId"
								:rules="[
									{
										required: true,
										message: '请选择断路器类型'
									}
								]"
							>
								<el-select
									v-model="basicForm.fkEquipmentModelId"
									clearable
									placeholder="请输入"
								>
									<el-option
										v-for="item in chopperTypes"
										:key="item.pkBasicdataId"
										:value="item.pkBasicdataId"
										:label="item.itemName"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
                        <el-col span="8">
                            <el-form-item
                                label="断路器线路"
                                prop="line"
                                :rules="[
                                    {
                                        required: true,
                                        message: '请选择断路器线路'
                                    }
                                ]">
                                <el-select
                                    v-model="basicForm.line"
                                    clearable
                                    placeholder="请输入"
                                >
                                    <el-option v-for="item in 6" :key="item" :label="'线路:'+item" :value="item"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
					</template>
					<el-col :span="8" :hidden="isUpdate">
                            <el-form-item v-if="!basicForm.thirdPartyDeviceId" label-width="0">
                                <el-button
								:disabled="isUpdate"
								:hidden="isUpdate"
                                @click="getEquipment"
                                :loading="LoadingState"
                                >获取设备信息{{
                                    LoadingState ? '中' : ''
                                }}</el-button>
                            </el-form-item>
						<el-tag type="success" v-else>设备获取成功</el-tag>
					</el-col>
				</el-row>
			</el-form>
			<el-row justify="center" style="margin-top: 0.2rem">
				<el-col :span="4" :offset="10">
					<el-button
						type="primary"
						@click="submitForm"
						:loading="hasSubmit"
						>确定</el-button
					>
					<el-button @click="colse">取消</el-button>
				</el-col>
			</el-row>
		</div>
	</div>
</el-scrollbar>
</template>

<script>
import {
	getBuildingName,
	getAllAreaNumber,
} from "@/api/house/building/building.js";
import { getOneAll, selectNameToId, getAllByTwo } from "@/api/common/common.js";
import {
	addByDevice,
	getDeviceById,
    getThirdPartyUuid,
    getThirdPartyToken,
    getYunDingTokenUrl,
    getWeiYuTokenUrl,
    getLuMiTokenUrl,
	updateByDevice
} from "@/api/operations/device";

export default {
	data() {
		return {
			//设备按钮获取状态 获取中 true 没在获取中 false
			LoadingState: false,
			loading: false,
			hasSubmit: false,
			isUpdate: false, //是否修改
			basicForm: {
				region: null,
                line:null,
			},
			building: [], //楼宇
			rooms: [], //区域
			equipment: [], //设备类别
			rules: {},
			chopperTypes: [],
		};
	},
	computed: {
		//是否选中断路器
		isChopper() {
			return (
				this.basicForm.fkEquipmentTypeId ==
				"weiyu.circuit_breaker"
			);
		},
	},
	methods: {
		getEquipment() {
			if (!this.basicForm.fkEquipmentTypeId) {
				this.$message.warning("请先选择设备类型");
				return;
			}
			if (!this.basicForm.equipmentSerialNumber) {
				this.$message.warning("请先输入设备序列号");
				return;
			}
			this.LoadingState = true;
			let uuidObj = {
				equipmentSerialNumber: this.basicForm.equipmentSerialNumber,
				fkEquipmentTypeId: this.basicForm.fkEquipmentTypeId,
			};
			if (this.basicForm.fkEquipmentModelId) {
				uuidObj.equipmentModel = this.basicForm.fkEquipmentModelId;
            }
            /**
             * 约定
             * 根据类型判断是绿米 或者 云丁 ....
             * 获取 token 判断非空 空则请求第三方，然后存token至后端
             * 有token 则加上条件 获取设备信息 后拿到第三方特定id 存给 thirdPartyDeviceId
             * 
             * luMi 相对复杂
             * */
            let typeKey = this.basicForm.fkEquipmentTypeId.split(".")[0];
            switch(typeKey){
                case "lumi":
                    this.luMiTest();
                break;
                case "weiyu":
                    this.WeiYuTest();
                break;
                case "yunding":
                    this.yunDingTest();
                break;
            }
        },
        yunDingTest(){
            let token = null;
            /**
             * 先从后端取token
             * 有：不需要存token
             * 无：第三方取token。取后存给后端
             */
            getYunDingTokenUrl().then(res=>{
                return new Promise((reslove,reject)=>{
                    if(res.data.yunDingToken){
                        token = res.data.yunDingToken;
                        reslove();
                    }else{
                        axios.post(res.data.url,res.data).then((res)=>{
                            if(res.ErrNo===0){
                                token = res.access_token;
                                getThirdPartyToken({
                                    yunDingToken:token
                                }); 
                                reslove();
                            }else{
                                reject(res.ErrMsg);
                            }
                        });
                    }
                });
            }).then(res=>{   
                /**
                 * 水表id少于14位 需要id前面填“0” 电表无限制
                 */
                let id = this.basicForm.equipmentSerialNumber;
                if(this.basicForm.fkEquipmentTypeId == "yunding.water_meter"){
                    if(id.length<14){
                        let fSize = 14-(id.length);
                        for(let i = 0;i<fSize;i++){
                            id = "0" + id;
                        }
                    }
                }
				
                return axios.get("/queryYunDing",{params:{access_token:token,sn:id}})
            }).then(res=>{
                if(res.ErrNo==0){
                    this.basicForm.thirdPartyDeviceId = res.result.uuid;
                }else{
                    return Promise.reject(res.ErrMsg);
                }
            }).catch(res=>{
                this.$message.error(res);
            }).finally(()=>{
                this.LoadingState = false;
            });
        },
        WeiYuTest(){
            let token = null;
            getWeiYuTokenUrl().then(res=>{
                if(!this.basicForm.fkEquipmentModelId){
                    this.$message.warning("请先选择断路器类型");
                    return;
                }
                return new Promise((reslove,reject)=>{
                    if(res.data.weiYuToken){
                        token = res.data.weiYuToken;
                        reslove();
                    }else{
                        axios.get(res.data.url,res.data).then((res)=>{
                            if(!res.errorcode){
                                token = res.data.access_token;
                                getThirdPartyToken({
                                    weiYuToken:token
                                });
                                reslove();
                            }else{
                                reject(res.msg);
                            }
                        });
                    }
                });
            }).then(res=>{   
                let typeName = this.chopperTypes.filter(v=>v.pkBasicdataId==this.basicForm.fkEquipmentModelId)[0].itemName;
				return axios({
                    method: 'get',
                    url: `/queryWeiYu/${typeName}/${this.basicForm.equipmentSerialNumber}`,
                    headers: { 'authorization': token ,"token":null}
                });
            }).then(res => {
                if(res.errorcode==null || res.errorcode==''){
                    /**
                     * 微语不需要存 第三方ID 则存占位符就行了
                     */
                    this.basicForm.thirdPartyDeviceId = "0";
                }else{
                    return Promise.reject(res.msg);
                }
            }).catch(res=>{
                this.$message.error(res);
            }).finally(()=>{
                this.LoadingState = false;
            });
        },
        luMiTest(){
            /**
             * 绿米有 code 和 refresh_token 
             * 需要先获取 code
             */
            let token = null;
            //获取设备参数
            let inquireMap = null;
            let parameterMap = null;
            getLuMiTokenUrl().then(res=>{
                return new Promise((resolve,reject)=>{
                    //有codeUrl时inquireMap为空 普通有tokenUrl或token时inquireMap,paramenterMap有值
                    inquireMap = res.data.inquireMap;
                    parameterMap = res.data.parameterMap;
                    if(res.data.luMiAccessToken){
                        token = res.data.luMiAccessToken;
                        resolve();
                    }else{
                        let token_url = null;
                        new Promise((resolve,reject)=>{    
                            // 如果后端返回 codeUrl 代表需要先重新获取 code 
                            if(res.data.codeUrl){
                                axios({
                                    method: 'post',
                                    url:res.data.codeUrl,
                                    headers: {
                                        'Content-Type': 'application/json'
                                    },
                                    data: res.data.codeParameter,
                                    params:res.data.codeParameter
                                }).then(codeResult=>{
                                    if(codeResult.code==0){
                                        //根据 code 获取 token 获取路径
                                        getLuMiTokenUrl({code:codeResult.result.authorizationCode})
                                        .then(tokenUrlResult=>{
                                            token_url = tokenUrlResult.data.luMiAccessTokenUrl;
                                            inquireMap = tokenUrlResult.data.inquireMap;
                                            parameterMap = tokenUrlResult.data.parameterMap;
                                            resolve();
                                        })
                                    }else{
                                        reject(codeResult.message);
                                    }
                                });
                            }else{
                                token_url = res.data.luMiAccessTokenUrl;
                                resolve();
                            }
                        }).then(()=>{
                            axios({
                                method: 'post',
                                url:token_url,
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                                },
                                data:parameterMap,
                                params:parameterMap
                            }).then(token_res=>{
                                //判断获取token情况 然后传给后端特定 token
                                switch(parameterMap.grant_type){
                                    //刷新token
                                    case "refresh_token":
                                        getThirdPartyToken({
                                            luMiAccessToken:token_res.access_token
                                        });
                                    break;
                                    //获取token
                                    case "authorization_code":
										getThirdPartyToken({
                                            luMiAccessToken:token_res.access_token,
                                            luMiRefreshToken:token_res.refresh_token,
                                        });
                                    break;
                                }
                                token = token_res.access_token;
                                resolve();
                            })
                        });
                    }
                })
            }).then(res=>{
                inquireMap.Accesstoken = token;
                return axios.get("/queryLuMi",{
                    params:{did:this.basicForm.equipmentSerialNumber},
                    headers:inquireMap
                })
            }).then(lmResult=>{
                if(lmResult.code == 0){
                    this.basicForm.thirdPartyDeviceId = lmResult.result.data[0].did;
                    this.basicForm.equipmentTypeName = lmResult.result.data[0].model;
                }else{
                    return Promise.reject(lmResult.message);
                }
            }).catch(msg=>{
                this.$message.error(msg);
            }).finally(()=>{
                this.LoadingState = false;
            });
        },
		changeBuilding(id) {
            if (id) {
				getAllAreaNumber(id).then(res => {
					this.rooms = res.data.roomList;
					this.rooms.unshift({ pkRoomId: '0', houseNumber: '公共区域' });
					this.basicForm.region = null;
				});
			} else {
				this.rooms = [];
				this.basicForm.region = null;
			}
		},
		loadDetail(id) {
			this.loading = true;
			getDeviceById(id)
            .then((res) => {
                this.basicForm = res.data;
                getAllAreaNumber(this.basicForm.fkBuildingId).then(res => {
                    this.rooms = res.data.roomList;
                    this.rooms.unshift({ pkRoomId: '0', houseNumber: '公共区域' });
                });
            })
            .finally(() => {
                this.loading = false;
            });
		},
		submitForm() {
			this.$refs["basicForm"].validate((valid) => {
				if (valid) {
					if (!this.isUpdate && !this.basicForm.thirdPartyDeviceId ) {
						this.$message.warning("请先获取设备Id");
						return;
					}
					//状态后改
					this.hasSubmit = true;
					if (this.isUpdate) {
						updateByDevice(this.basicForm)
							.then((result) => {
								if (result.code === 10000) {
									this.$message.success(result.msg);
									this.colse();
								}
							})
							.finally((_) => {
								this.hasSubmit = false;
							});
					} else {
						addByDevice(this.basicForm)
							.then((result) => {
								if (result.code === 10000) {
									this.$message.success(result.msg);
									this.colse();
								}
							})
							.finally((_) => {
								this.hasSubmit = false;
							});
					}
				}
			});
		},
		colse() {
			window.history.go(-1);
		},
		Init() {
			let types = new Promise((resolve, reject) => {
				getAllByTwo("weiyu.circuit_breaker").then((res) => {
					this.chopperTypes = res.data;
					resolve();
				});
			});
			let buildings = new Promise((resolve, reject) => {
				getBuildingName().then((res) => {
					this.building = res.data;
					resolve();
				});
			});
			let equipments = new Promise((resolve, reject) => {
				getOneAll(selectNameToId("equipment")).then((res) => {
					this.equipment = res.data;
					resolve();
				});
			});
			Promise.all([buildings, equipments, types]).then(() => {
				let id = this.$route.query.id;
				if (id) {
					this.isUpdate = true;
					this.loadDetail(id);
				}
			});
		}
	},
	mounted() {
        this.Init();
	},
};
</script>
<style scoped>
</style>
